/*
 * @Author: taoyuqing
 * @Date: 2022-12-23 01:03:24
 * @Description: vip页面
 */

import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:spree/utils/api.dart';
import 'package:spree/utils/resp_code_enum.dart';
import 'package:spree/utils/utils.dart';
import 'package:spree/widgets/common_container.dart';
import 'package:spree/widgets/progress_bar.dart';
import 'package:spree/widgets/vip_content_box.dart';
import 'package:spree/widgets/vip_rectangle_box.dart';
import 'package:spree/widgets/vip_step.dart';

import '../provider/model/user_model.dart';
import 'games/rules_banner.dart';

class VIPPage extends StatefulWidget {
  VIPPage({Key? key}) : super(key: key);

  @override
  State<VIPPage> createState() => _VIPPageState();
}

class _VIPPageState extends State<VIPPage> with AutomaticKeepAliveClientMixin {
  final GlobalKey<RulesBannerState> _globalKey = GlobalKey();
  dynamic userAccount;
  int level = 0;
  int nextLevel = 0;
  String levelImg = "images/vipLevel/level_0.png";
  double currentDepositAmount = 0.0;
  double nextVipDepositAmount = 0.0;
  double depositPercent = 0.0;
  double currentBetAmount = 0.0;
  double nextVipBetAmount = 0.0;
  double betPercent = 0.0;
  double nextLevelNeedDeposit = 0.0;
  double nextLevelNeedBet = 0.0;
  List<Widget> _vipIntroduceList = [];
  int _curIndex = 0;
  @override
  void initState() {
    // TODO: implement initState
    String? userId = context.read<UserModel>().userId;
    if (userId != '') {
      initAccountInfo();
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('VIP page'),
      ),
      body: CommonContainer(
        child: ListView(
          padding: EdgeInsets.only(top: 20),
          children: [
            VipContentBox(
              child: Column(
                children: [
                  // 文字部分
                  Container(
                    child: Column(
                      children: [
                        Text(
                          'YOUR VIP LEVEL IS ',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 15,
                              fontWeight: FontWeight.w700),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 8, bottom: 8),
                          child: Text(
                            'LEVEL $level',
                            style: TextStyle(
                                color: Color(0xffFFED4A),
                                fontSize: 15,
                                fontWeight: FontWeight.w700),
                          ),
                        ),
                        Image.asset(
                          '$levelImg',
                          width: 50,
                        )
                      ],
                    ),
                  ),
                  ProgressBar(
                    percent: depositPercent,
                    name: 'Deposit Amount',
                    cur: '\$' + currentDepositAmount.toString(),
                    totle: '/\$' + nextVipDepositAmount.toString(),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 26),
                    child: ProgressBar(
                      percent: betPercent,
                      name: 'Bet Amount',
                      cur: '\$' + currentBetAmount.toString(),
                      totle: '/\$' + nextVipBetAmount.toString(),
                    ),
                  ),
                  //  文字部分
                  Container(
                    margin: EdgeInsets.only(top: 30),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              'Upgrading to',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                  fontWeight: FontWeight.w700),
                            ),
                            Text(
                              'VIP $nextLevel',
                              style: TextStyle(
                                  color: Color(0xffFFED4A),
                                  fontSize: 15,
                                  fontWeight: FontWeight.w700),
                            ),
                            Text(
                              'also',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                  fontWeight: FontWeight.w700),
                            ),
                          ],
                        ),
                        Text(
                          'requires:',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 15,
                              fontWeight: FontWeight.w700),
                        ),
                      ],
                    ),
                  ),
                  _vipRectBox(
                      name: 'BET', totle: '\$' + nextLevelNeedBet.toString()),
                  _vipRectBox(
                      name: 'DEPOSIT',
                      totle: '\$' + nextLevelNeedDeposit.toString())
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 20),
              child: VipContentBox(
                child: Container(
                  padding: EdgeInsets.only(left: 20, right: 20),
                  child: Column(
                    children: [
                      Container(
                        height: 100,
                        width: Utils().getScreenWidth(context),
                        child: ListView(
                          scrollDirection: Axis.horizontal,
                          children: [VipStep()],
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 15, bottom: 10),
                        child: Text(
                          'The Betspree VIP level system is created with 10 levels, each with a corresponding cash prize. The more you play, the higher the VIP level and the more you will receive.',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              fontWeight: FontWeight.w700),
                        ),
                      ),
                      _vipRectBox(
                          name: 'Accumulated Bet Amount',
                          totle: '\$' + currentBetAmount.toString(),
                          color: Color(0xffFFED4A)),
                      _vipRectBox(
                          name: 'Accumulated Deposit Amount',
                          totle: '\$' + currentDepositAmount.toString(),
                          color: Color(0xffFFED4A)),
                    ],
                  ),
                ),
              ),
            ),
            Stack(
              clipBehavior: Clip.none,
              children: [
                Container(
                  margin: EdgeInsets.only(top: 20),
                  child: VipContentBox(
                    padding: EdgeInsets.only(top: 5, bottom: 20),
                    width: Utils().getScreenWidth(context),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        _vipRectBox(
                            name: 'Original Games',
                            totle: '0%',
                            color: Color(0xffFFED4A),
                            width: 250),
                        _vipRectBox(
                            name: 'Accumulated Deposit ',
                            totle: 'Amount 0 %',
                            color: Color(0xffFFED4A),
                            width: 250),
                      ],
                    ),
                  ),
                ),
                Positioned(
                    bottom: -20,
                    child: Image.asset(
                      'images/money.png',
                      width: 100,
                    ))
              ],
            ),
            _levelIntroduce(
                level: '01',
                imgPath: 'images/money-bag.png',
                introduce:
                    'Place a bet on an original or LIVE game and the MONEY BACK engine will automatically calculate the return value based on your VIP level as you enjoy the game.'),
            _levelIntroduce(
                level: '02',
                imgPath: 'images/new-year-time.png',
                introduce:
                    'The cash back mechanism will be settled on your account balance at 0:00 based on your bets placed throughout the day.'),
            _levelIntroduce(
                level: '03',
                imgPath: 'images/strategy.png',
                introduce:
                    'The more you play, the higher your money back, for example your [VIP1] cumulative level bet of €10,000 will bring you a €20 back bonus. (The return for vip10 is R\$50)'),
            // _vipIntroduce('10',totalBets: '40000000',totalDeposits: '10000000'),
            // _vipIntroduce('0',totalBets: '100',totalDeposits: '0.0'),
            RulesBanner(
              key: _globalKey,
              height: 720,
              index: _curIndex,
              onchange: (i) {
                setState(() {
                  _curIndex = i;
                });
              },
              imageList: _vipIntroduceList,
              // [
              //   _vipIntroduce(8, totalBets: 40000000, totalDeposits: 10000000),
              //   _vipIntroduce(0, totalBets: 100, totalDeposits: 0.0),
              //   _vipIntroduce(1, totalBets: 10000000, totalDeposits: 40000000),
              //   _vipIntroduce(2, totalBets: 10000000, totalDeposits: 40000000),
              // ]
            ),
          ],
        ),
      ),
    );
  }

  initAccountInfo() async {
    dynamic result = await Api.account();
    if (result['code'] == RespCode.SUCCESS.code) {
      userAccount = result['data'];
      level = userAccount['vipLevel'];
      currentDepositAmount = userAccount['depositAmount'];
      dynamic nextVipLevel = userAccount['nextVipLevelConfig'];
      nextVipDepositAmount = nextVipLevel['depositAmount'];
      String tempDepositPercent =
          (currentDepositAmount / nextVipDepositAmount).toStringAsFixed(2);
      depositPercent = double.parse(tempDepositPercent);
      if (depositPercent > 1) {
        depositPercent = 1;
      }
      currentBetAmount = userAccount['betAmount'];
      nextVipBetAmount = nextVipLevel['vestAmount'];
      String tempBetPercent =
          (currentBetAmount / nextVipBetAmount).toStringAsFixed(2);
      betPercent = double.parse(tempBetPercent);
      if (betPercent > 1) {
        betPercent = 1;
      }
      levelImg = "images/vipLevel/level_$level" + ".png";
      nextLevel = nextVipLevel['level'];
      nextLevelNeedBet = nextVipBetAmount - currentBetAmount;
      if (nextLevelNeedBet <= 0) {
        nextLevelNeedBet = 0;
      }
      nextLevelNeedDeposit = nextVipDepositAmount - currentDepositAmount;
      if (nextLevelNeedDeposit <= 0) {
        nextLevelNeedDeposit = 0;
      }
      List vipConfigs = userAccount['vipConfigs'];
      initVipIntroduce(vipConfigs);
      setState(() {});
    }
  }

  List<Widget> initVipIntroduce(List vipConfigs) {
    for (int i = 0; i < vipConfigs.length; i++) {
      int level = vipConfigs[i]['level'];
      double totalBets = vipConfigs[i]['vestAmount'];
      double totalDeposit = vipConfigs[i]['depositAmount'];
      double rate = vipConfigs[i]['rate'];
      int withdrawLimit = vipConfigs[i]['withdrawTimes'];
      double handleForFree = vipConfigs[i]['handlingFeeForFree'];
      double maxWithdrawAmount = vipConfigs[i]['perWithdrawMaxAmount'];
      double levelProtection = vipConfigs[i]['gradingDepositAmount'];
      _vipIntroduceList.add(_vipIntroduce(
        level,
        totalBets: totalBets,
        totalDeposits: totalDeposit,
        rate: rate,
        withdrawLimit: withdrawLimit,
        freeWithdrawAmount: handleForFree,
        maxWithdrawAmount: maxWithdrawAmount,
        levelProtection: levelProtection,
      ));
    }
    return _vipIntroduceList;
  }

  Widget _vipRectBox(
      {String? name,
      String? totle,
      Color? color = const Color(0xFFffffff),
      double? width}) {
    double widgetWidth = width ?? Utils().getScreenWidth(context);
    return Container(
      margin: EdgeInsets.only(top: 15),
      padding: EdgeInsets.only(left: 20, right: 20),
      width: widgetWidth,
      child: VipRectangleBox(
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 10),
              child: Text(
                name ?? '',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.w700),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 4, bottom: 10),
              child: Text(
                totle != null ? '$totle' : '',
                style: TextStyle(
                    color: color, fontSize: 15, fontWeight: FontWeight.w700),
              ),
            )
          ],
        ),
      ),
    );
  }

  _vipIntroduce(int level,
      {double? totalBets,
      double? totalDeposits,
      double? levelProtection,
      int? withdrawLimit,
      double? maxWithdrawAmount,
      double? rate,
      double? freeWithdrawAmount}) {
    return VipContentBox(
      padding: EdgeInsets.all(20),
      margin: EdgeInsets.only(top: 30),
      child: Column(
        children: [
          Image.asset(
            'images/vipLevel/level_$level.png',
            width: 50,
          ),
          Padding(
            padding: EdgeInsets.only(top: 12),
            child: Text(
              'VIP $level',
              style: TextStyle(
                  color: Color(0xFFFFD338),
                  fontSize: 22,
                  fontWeight: FontWeight.w700),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 12),
            child: Text(
              'Update Conditions',
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.w700),
            ),
          ),
          _vipRectBox(name: 'Total bets', totle: 'R\$ $totalBets'),
          _vipRectBox(name: 'Total deposits', totle: 'R\$ $totalDeposits'),
          Padding(
            padding: EdgeInsets.only(top: 12),
            child: Text(
              'LEVEL PROTECTION',
              style: TextStyle(
                  color: Color(0xFFFFD338),
                  fontSize: 22,
                  fontWeight: FontWeight.w700),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 12),
            child: Text(
              'DEPOSIT R\$ $levelProtection/MONTH',
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.w700),
            ),
          ),
          Divider(
            color: Colors.white70,
          ),
          Padding(
            padding: EdgeInsets.only(top: 12),
            child: Text(
              'WITHDRAWAL PRIVILEGES',
              style: TextStyle(
                  color: Color(0xFFFFD338),
                  fontSize: 22,
                  fontWeight: FontWeight.w700),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 12),
            child: Text(
              'Number of withdrawals.: $withdrawLimit /day',
              style:
                  TextStyle(color: Colors.white, fontWeight: FontWeight.w700),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 12),
            child: Text(
              'Maximum withdrawals: R\$ $maxWithdrawAmount',
              style:
                  TextStyle(color: Colors.white, fontWeight: FontWeight.w700),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 12),
            child: Text(
              'Withdrawal fee: $rate%',
              style:
                  TextStyle(color: Colors.white, fontWeight: FontWeight.w700),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 12),
            child: Text(
              'Free withdrawal amount: R\$ $freeWithdrawAmount',
              style:
                  TextStyle(color: Colors.white, fontWeight: FontWeight.w700),
            ),
          ),
          Divider(
            color: Colors.white70,
          ),
          Padding(
            padding: EdgeInsets.only(top: 12),
            child: Text(
              'CashBack',
              style: TextStyle(
                  color: Color(0xFFFFD338),
                  fontSize: 22,
                  fontWeight: FontWeight.w700),
            ),
          ),
          Container(
            width: Utils().getScreenWidth(context),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'DICE: 0.50%',
                  style: TextStyle(color: Colors.white),
                ),
                Text(
                  'CRASH: 0.50%',
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 20),
            width: Utils().getScreenWidth(context),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'PLINKO: 0.50%',
                  style: TextStyle(color: Colors.white),
                ),
                Text(
                  'Limbo: 0.55%',
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _levelIntroduce(
      {required String level, required String imgPath, String? introduce}) {
    return Container(
      margin: EdgeInsets.only(top: 30),
      child: VipContentBox(
        child: Container(
          padding: EdgeInsets.only(left: 20, right: 20),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    level,
                    style: TextStyle(
                        color: Color.fromRGBO(0, 0, 0, 0.3),
                        fontSize: 60,
                        fontWeight: FontWeight.w800),
                  ),
                  Container(
                    child: Image.asset(
                      imgPath,
                      width: 100,
                    ),
                  )
                ],
              ),
              Text(
                introduce ?? '',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.w700),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => false;
}
